<?php

include_once "attributes.php";
include_once("../debug.php");

class pptrendsParser {

	var $error = "";     // Fehlermeldung fals eine Methode false zur?fert

	var $dbusername  = "";
	var $dbpassword  = "";
	var $dbname      = "";
	var $dbhost      = "";
	var $tablename   = ""; // PP Trends Tabelle
	var $pstatsname	 = ""; // player stats table
	
	var $parserarray = null;

	/**
	* @return downloads
	* @param String $dbusername Datenbanknutzername
	* @param String $dbpassword Datenbankpasswort
	* @param String $dbname Name der Datenbank
	* @param String $tablename Name der Tabelle mit den Downloads
	* @param String $dbhost Datenbankadresse
	* @desc Konstruktor der Klasse downloads
 	*/
	function pptrendsParser($dbusername,$dbpassword,$dbname,$tablename,$plstatstable,$dbhost="localhost") {

		if (!($this->_set_dbusername($dbusername))) die($this->error);
		if (!($this->_set_dbname($dbname))) die($this->error);
		if (!($this->_set_tablename($tablename))) die($this->error);
		$this->pstatsname = (!empty($plstatstable)) ? $plstatstable : "tabelle3";
		$this->dbpassword = $dbpassword;
		$this->_set_dbhost($dbhost);
		$this->_db_connection_works(); // Testen der Datenbankverbindung
	}


	function parseString($ppstring,$return=false) {
		global $default_server;
		$userid = $_SESSION['s_userid'];
		$ogameserver = $_SESSION['s_ogameserver'];

		$returnarray = array(); // wird ben?t bei return = true;

		$ppstring = trim($ppstring);
		
		$string = $ppstring;

		$matches = array();
		
		//@todo new version of ogame has added "统计 (更新时间: 2007-04-15, 03:08)" in stat page, try to use this data to judge whether stats has been changed or not
		if($ogameserver == 'ogame.com.cn') {
			$_ntitle = "/排名\s+玩家\s+联盟\s+积分/";
			$_nwm = "写入讯息";
			$_nsub = "–";			
		} else if($ogameserver == 'ogame.org') {
			$_ntitle = "/Rank\s+Player\s+Alliance\s+Points/";
			$_nwm = "write message";
			$_nsub = "–";			
		} else if($ogameserver == 'ogame.tw') {
			$_ntitle = "/排名\s+玩家\s+聯盟\s+積分/";
			$_nwm = "寫入訊息";
			$_nsub = "–";
		}

		
		if(preg_match($_ntitle, $string, $matches) != 1) {
			$this->error = "not a valid player rank/points report, parse failed.";
			return false;
		}
		$_ntitle = $matches[0];
		$string = trim(substr($string, strpos($string, $_ntitle)+strlen($_ntitle)));
		$isIE = false;
		if(strpos($_ntitle, "\t") === false)
			$isIE = true;

		$lines = explode("\n",$string);

		$infoarray = array();
		
		$pattern = "/^(\d+)\s+(\+|" . $_nsub . "|\*)\s+([^\t]+)\s+(?:". $_nwm . ")?\s+([^\t]*)\s+([\d\.]+)$/";
		$pattern_ie = "/^(\d+)\s+(\+|" . $_nsub . "|\*)\s+(.+)\s\s+(.*)\s([\d\.]+)\s$/";

		if($isIE)
			$pattern = $pattern_ie;
		$max = (count($lines)<100 ? count($lines) : 100);
		for ($i=0;$i<$max;$i++) {
			$ally          = "";
			$playername    = "";
			$rank  = 0;
			$points   = 0;
			
			$line = $lines[$i];
			if(preg_match($pattern, $line, $matches) == 1) {
				$rank = $matches[1];
				$status = $matches[2];
				$playername = trim($matches[3]);
				$ally = trim($matches[4]);
				$points = str_replace(".", "", $matches[5]);
				if($status != '+' && $status != '*') $status='-';
				$infoarray[] = array($rank, $playername, $ally, $points, $status);
			}
		}
	
		// DB Verbindung erstellen
		mysql_connect($this->dbhost, $this->dbusername, $this->dbpassword) or die(PARSER_ERROR3);
		mysql_select_db($this->dbname) or die(PARSER_ERROR2);

		$minrank = 65535;
		$maxrank = -1;
		$minpoints = -1;
		$maxpoints = -1;
		$adddate = date("Y-m-d H:i:s");
		// check whether these data has been upload or not
		$changed = false;
		foreach ($infoarray as $data) {
			$rank = (int)($data[0]);
			$playername = mysql_real_escape_string($data[1]);
			$points = (int)($data[3]);
			$query = "select rank from $this->tablename where userid=$userid and playername='$playername' and rank=$rank and points=$points";
			$res = mysql_query($query);
			if(!$res) {
				$this->error = $query." ".mysql_error();
				return false;
			} else if (!mysql_fetch_row($res)) {
				$changed = true;
				break;
			}
		}
		if (!$changed) {
			$this->error = "These rank/points data has been uploaded.";
			return false;
		}
		if ($changed && count($infoarray) > 0)
		foreach ($infoarray as $data) {
			$rank = (int)($data[0]);
			$playername = mysql_real_escape_string($data[1]);
			$ally = mysql_real_escape_string($data[2]);
			$points = (int)($data[3]);
			
			$minrank = min($minrank, $rank);
			$maxrank = max($maxrank, $rank);
			$minpoints = ($minpoints == -1 ? $points : min($points,$minpoints));
			$maxpoints = max($maxpoints, $points);
			$query = "select ind from $this->tablename where userid=$userid and playername='$playername'";
			$res = mysql_query($query);
			if (!$res) {
				$this->error = $query." ".mysql_error();
				return false;
			} else if ($row = mysql_fetch_object($res)) {
				$oind = $row->ind;
				$nind = ($oind+1==15 ? 1 : $oind+1);
				$query = " UPDATE $this->tablename "."SET allyname='$ally', rank=$rank, points=$points, ind=$nind, rank_$nind=$rank, points_$nind=$points, update_$nind='$adddate', last_update='$adddate'".
				" where userid=$userid and playername='$playername'";
				if (!$return) {
					mysql_query($query) or die(mysql_error());
				} else
					$returnarray = array_push($query);
			} else { // insert a new empty record
				$query = "INSERT INTO $this->tablename (userid, playername, allyname, rank, points, ind, rank_1, points_1, update_1, last_update) ".
				" values($userid, '$playername', '$ally', $rank, $points, 1, $rank, $points, '$adddate', '$adddate')";
				if (!$return) {
					mysql_query($query) or die(mysql_error());
				} else
					$returnarray = array_push($query);
			}
			// update $pstablename
			$query = "INSERT IGNORE INTO $this->pstatsname (userid, playername) values($userid, '$playername')";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}
			
			$query = "UPDATE $this->pstatsname set points=$points, ally='$ally', rank=$rank, last_update='$adddate' WHERE userid=$userid and playername='$playername'";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}
		}
	
		
		echo "<a style=\"color:#c4c4c4;\" href=\"pptrendsview.php" . ($maxpoints>-1 ? "?gepoints=$minpoints&lepoints=$maxpoints" : "") . "\">". count($infoarray) . ($maxrank > -1 ? " [$minrank..$maxrank] " : " ") . "pieces of rank records were parsed successfully." . "</a><br>";

		if ($return) return $returnarray;
		else return true;
	}


	/**
	* @return boolean
	* @param String $tablename Name der Tabelle mit den Downloads
	* @desc Setzt den Tabellennamen f? Datenbankverbindung
    */
	function _set_tablename($tablename) {
		if (!empty($tablename)) {
			$this->tablename = $tablename;
			return true;
		} else {
			$this->error = "Der Tabellenname ist leer!";
			return false;
		}
	}


	/**
	* @return boolean
	* @param String $dbusername Datenbanknutzername
	* @desc Setzt den Username f? Datenbankverbindung
    */
	function _set_dbusername($dbusername) {
		if (!empty($dbusername)) {
			$this->dbusername = $dbusername;
			return true;
		} else {
			$this->error = "Der Username ist leer!";
			return false;
		}
	}

	/**
	* @return boolean
	* @param String $dbpassword Datenbankpasswort
	* @desc Setzt das Passwort f? Datenbankverbindungen
 	*/
	function _set_dbpassword($dbpassword) {
			$this->dbpassword = $dbpassword;
			return true;
	}

	/**
	* @return boolean
	* @param String $dbname Datenbankname
	* @desc Setzt den Namen der zu verwendenden Datenbank
 	*/
	function _set_dbname($dbname) {
		if (!empty($dbname)) {
			$this->dbname = $dbname;
			return true;
		} else {
			$this->error = "Der Datenbankname ist leer!";
			return false;
		}
	}

	/**
	* @return boolean
	* @param String $dbhost Datenbankadresse
	* @desc Setzt die Host-Adresse f? Datenbank
 	*/
	function _set_dbhost($dbhost) {
		$this->dbhost = $dbhost;
		return true;
	}

	/**
	* @return boolean
	* @desc Testet ob die Verbindung zur Datenbank funktioniert
 	*/
	function _db_connection_works() {
		mysql_connect($this->dbhost, $this->dbusername, $this->dbpassword) or die(PARSER_ERROR3);
		mysql_select_db($this->dbname) or die(PARSER_ERROR2);
		mysql_close();
		return true;
	}

}




?>